package com.mall.huohuo.common.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.lang.Assert;

import java.util.Date;
import java.util.Map;


public class JwtUtils {


    /**
     * secret key
     */
    private static String secretKey = "SecretKey01234588678901234567890123456789012345678901234567890123456789";

    /**
     * Token validity time(ms)
     */
    // private static long tokenValidityInMilliseconds = 1000 * 60 * 120L;

    /**
     * Create token
     *
     * @param claims        claim
     * @param expireSeconds 过期秒数
     * @return token
     */
    public static String createToken(Map<String, Object> claims, long expireSeconds) {
        Assert.isTrue(expireSeconds > 0, "要生成的token过期时间不能为0。");
        /**
         * Current time
         */
        long now = (new Date()).getTime();
        /**
         * Validity date
         */
        Date validity;
        validity = new Date(now + expireSeconds * 1000);

        JwtBuilder jwtBuilder = Jwts.builder().setExpiration(validity).signWith(SignatureAlgorithm.HS256, secretKey);

        claims.forEach((k, v) -> jwtBuilder.claim(k, v));

        /**
         * create token
         */
        return jwtBuilder.compact();
    }

    /**
     * 根据token获取用户
     *
     * @param token token
     * @return 用户
     */
    public static Claims getClaims(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();

            return claims;
        } catch (ExpiredJwtException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * validate token
     *
     * @param token token
     * @return whether valid
     */
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            throw  e;
        }
    }
}
